# -*- coding: utf-8 -*-
"""
__author__ = 'Chenshuchuan'
"""
from flask_restful import abort
import json
import jwt
import time
from datetime import date, datetime, timedelta
from app_config import AUTH_REFRESH_TOKEN_SECRET, AUTH_TOKEN_SECRET, NGINX_HOST


class BaseCommon(object):

	def __init__(self):
		self.user = 'admin'

	def convert_to_dict(self, obj):
		"""把Object对象转换成Dict对象"""
		if obj is None:
			return {}
		dict = {}
		obj._sa_instance_state = ''
		dict.update(obj.__dict__)
		return dict

	def com_obj_dict(self, objs):
		data = []
		if len(objs) > 0:
			for obj in objs:
				obj = self.row_to_dict(obj)
				data.append(obj)
		return data

	def row_to_dict(self, row):
		d = {}
		for column in row.__table__.columns:
			if str(column.type) == "DATETIME":
				data = getattr(row, column.name)
				if data is None:
					d[column.name] = ''
				else:
					d[column.name] = str(getattr(row, column.name).strftime('%Y-%m-%d %H:%M:%S'))
			else:

				d[column.name] = getattr(row, column.name)
		return d

	def obj_to_view(self, obj, data):
		d = {}
		temp = data
		for column in obj.__table__.columns:
			if str(column.name) in temp:
				if str(column.type) == "DATETIME":
					data = getattr(obj, column.name)
					if data is None:
						d[column.name] = ''
					else:
						d[column.name] = str(getattr(obj, column.name).strftime('%Y-%m-%d %H:%M:%S'))
				else:
					d[column.name] = getattr(obj, column.name)
		return d

	def list_to_view(self, items, data=None):
		brr = []
		for item in items:
			if data is not None:
				brr.append(self.obj_to_view(item, data))
			else:
				brr.append(self.row_to_dict(item))
		return brr

	def byte_to_str(self, s):
		return str(s.decode())

	def refresh_encode(self, data):
		"""
		加密传输的数据
		:param data: dict
		:return:
		"""
		data["exp"] = datetime.now() + timedelta(days=7)
		return jwt.encode(data, AUTH_REFRESH_TOKEN_SECRET, algorithm='HS256')

	def refresh_decode(self, refresh_token):
		"""
		解密传输的数据
		:param refresh_token: 加密长字符串
		:return:
		"""
		try:
			data = jwt.decode(refresh_token, AUTH_REFRESH_TOKEN_SECRET)
		except Exception as e:
			return False
		if data:
			refresh_data = data
		else:
			refresh_data = dict()
		return refresh_data

	def encode(self, data):
		"""
		加密传输的数据
		:param data: dict
		:return:
		"""
		temp = dict()
		refresh_data = data
		time_now = (datetime.now() + timedelta(seconds=7200)).strftime("%Y-%m-%d %H:%M:%S")
		data["exp"] = time_now
		temp["exp"] = self.time_formart(time_now)
		temp["refresh_token"] = self.refresh_encode(refresh_data)
		temp["token"] = jwt.encode(data, AUTH_TOKEN_SECRET, algorithm='HS256')
		return temp

	def decode(self, data):
		"""
		解密传输的数据
		:param data: 加密长字符串
		:return:
		"""
		try:
			return jwt.decode(data, AUTH_TOKEN_SECRET)
		except Exception as e:
			abort(403, message="Signature verification failed")

	def time_formart(self, dt):
		timeArray = time.strptime(dt, "%Y-%m-%d %H:%M:%S")
		return time.mktime(timeArray)

	def sencode(self, s):
		return ' '.join([bin(ord(c)).replace('0b', '') for c in s])

	def sdecode(self, s):
		return ''.join([chr(i) for i in [int(b, 2) for b in s.split(' ')]])

	def show_file_url(self, url):
		if url in ["", None]:
			return ""
		return "/".join([NGINX_HOST, url])

	def show_base64_url(self, url):
		if url in ["", None]:
			return ""
		if type(url) == bytes:
			self.byte_to_str(url)
			return "".join(["data:image/jpeg;base64,", self.byte_to_str(url)])
		return "".join(["data:image/jpeg;base64,", url])

	def id2time(self, object_id):
		timeStamp = int(object_id[:8], 16)
		return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timeStamp))


# >> > encode('hello')
# '1101000 1100101 1101100 1101100 1101111'
# >> > decode('1101000 1100101 1101100 1101100 1101111')
# 'hello'


class DateEncoder(json.JSONEncoder):
	def default(self, obj):
		if isinstance(obj, datetime):
			return obj.strftime('%Y-%m-%d %H:%M:%S')
		elif isinstance(obj, date):
			return obj.strftime("%Y-%m-%d")
		else:
			return json.JSONEncoder.default(self, obj)
